package com.wealth.system.web.controller;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wealth.member.entity.Member;
import com.wealth.member.entity.Membership;
import com.wealth.member.service.IMemberService;
import com.wealth.member.service.IMembershipService;

/**
 * session中注入memberid
 * @author chan
 */
@Controller
@RequestMapping(value="/sessionInject")
public class SessionInjectController extends BaseController {
	
	@Autowired
	private IMembershipService membershipService;
	@Autowired
	private IMemberService memberService;
	
	/**
	 * 将memberid添加到session
	 */
	@RequestMapping(value="/memberid",method=RequestMethod.POST)
	@ResponseBody
	public String injectMemberid(
			@RequestParam(required=false) String openid,
			@RequestParam(required=false) String headimgurl,
			@RequestParam(required=false) String nickname,
			HttpSession session) {
		try {
			 if(StringUtils.isBlank(openid)){
				 return "fail";
			 }
			 
			Membership membership =  membershipService.getMemberShipByOpenidAndCorpId(openid, corpid);
			if(membership==null){
				//注册
				membership = memberService.reg(openid, headimgurl, nickname, corpid);
			}else{
				//修改头像和昵称
				Member member = membership.getMember();
				member.setNickname(nickname);
				member.setHeadimgurl(headimgurl);
				memberService.save(member);
			}
			
			session.setAttribute("memberid", membership.getMember().getId());
			
			return "success";
		} catch (Exception e) {
			return "fail";
		}
	}
}


